#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#include "ql_api_osi.h"
#include "ql_api_nw.h"

#include "ql_log.h"
#include "ql_api_datacall.h"
#include "ql_ntp_client.h"
#include "ql_api_rtc.h"
#include "zq_gl.h"

#define ZQ_RTC_FILE_PATH "UFS:/app/rtc_tmp.dat"			// 用于重连重启时的rtc时间, 断网重启后可以恢复。
static ql_task_t ntp_task = NULL;
static ntp_client_id  ntp_cli_id = 0;
static ql_sem_t  ntp_semp;

int ZqStoreRtc(void)
{
	int timezone;
	ql_rtc_time_t local = { 0 };
	ql_errcode_rtc_e ret = ql_rtc_get_time(&local);
	ret = ql_rtc_get_timezone(&timezone);
	if (ret != QL_RTC_SUCCESS) return -1;
	char rtctmp[24] = { 0 };
	sprintf(rtctmp, "%04d%02d%02d%02d%02d%02d, %02d", local.tm_year, local.tm_mon, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec, timezone);
	ZQLOG("za_StoreRtc rtctmp: [%s], zone: %d", rtctmp, timezone);
	zq_EasyFileWrite(ZQ_RTC_FILE_PATH, rtctmp, strlen(rtctmp));
	return 0;
}
int ZqLoadRtc(void)
{
	int timezone;
	ql_rtc_time_t local = { 0 };
	char timetmp[24] = { 0 };
	int ret = zq_EasyFileRead(ZQ_RTC_FILE_PATH, timetmp, sizeof(timetmp));
	ZQLOG("Load rtc store file ret: [%d], timetmp: [%s]", ret, timetmp);
	if (ret < 0) return -1;
	if ((ret > 0) && (sscanf(timetmp, "%04d%02d%02d%02d%02d%02d, %02d", &local.tm_year, &local.tm_mon, &local.tm_mday, &local.tm_hour, &local.tm_min, &local.tm_sec, &timezone) == 7)) {
		if ((local.tm_year >= 2024) && (local.tm_year <= 2100)) {
			ql_rtc_set_timezone(timezone);
			ql_rtc_set_time(&local);
			ql_remove(ZQ_RTC_FILE_PATH);
			// check results
			ql_rtc_get_time(&local);
			ql_rtc_get_timezone(&timezone);
			sprintf(timetmp, "%04d%02d%02d%02d%02d%02d, %02d", local.tm_year, local.tm_mon, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec, timezone);
			ZQLOG("Config rtc results: [%s]", timetmp);
			return 0;
		}
	}
	ZQLOG("Config rtc fail\n");
	return -1;
}

static void ntp_result_cb(ntp_client_id cli_id, int result, struct tm *sync_time, void *arg)
{
    ql_rtc_time_t time;
	if(ntp_cli_id != cli_id)
		return;

	if(result == QL_NTP_SUCCESS){
		char time_str[256] = {0};
		snprintf(time_str, 256, "%04d/%02d/%02d,%02d:%02d:%02d",sync_time->tm_year + 1900, sync_time->tm_mon + 1, sync_time->tm_mday,
                       sync_time->tm_hour, sync_time->tm_min, sync_time->tm_sec);
		ZQLOG("ntp sync time:%s", time_str);
	    time.tm_year = sync_time->tm_year+ 1900;
	    time.tm_mon  = sync_time->tm_mon + 1;
	    time.tm_mday = sync_time->tm_mday;
	    time.tm_wday = sync_time->tm_wday;
	    time.tm_hour = sync_time->tm_hour;
	    time.tm_min  = sync_time->tm_min;
	    time.tm_sec  = sync_time->tm_sec;
		if(ql_rtc_set_time(&time) != QL_RTC_SUCCESS)
		{
			ZQLOG("ntp set RTC time failed");
		}
	}
	else{
		ZQLOG("ntp sync failed :%d", result);
	}
	ql_rtos_semaphore_release(ntp_semp);
}

static void ntp_app_thread(void * arg)
{

	ql_rtos_semaphore_create(&ntp_semp, 0);
	
	// while(ql_datacall_get_sim_profile_is_active(ZQ_SIM_0, ZQ_PROFILE_IDX) != 1) // 等待sim卡激活
	// 	ql_rtos_task_sleep_s(5); 
	for(; ;ql_rtos_task_sleep_s(24*3600)) { // 24H校时一次
		zq_StartDataCall();
		int error_num = 0;
		ql_ntp_sync_option  sync_option;
		sync_option.pdp_cid = ZQ_PROFILE_IDX;
		sync_option.sim_id = ZQ_SIM_0;
		sync_option.retry_cnt = 3;			// 重试5次，间隔5s
		sync_option.retry_interval_tm = 5;
		ntp_cli_id = ql_ntp_sync("ntp.aliyun.com", &sync_option, ntp_result_cb, NULL, &error_num);
		if(ntp_cli_id != 0)
			ql_rtos_semaphore_wait(ntp_semp, QL_WAIT_FOREVER);
        else
			ZQLOG("ntp failed: err code = %d", error_num);
		// ql_rtc_time_t local;
		// ql_rtc_get_time(&local);
		// if (local.tm_year >= 2023 || timer > 5) timer = 24*3600; // 校时成功或者超过重试5次，24H校时一次, 
        // else timer++;
	}
   return;	
}


int zq_ntp_init(void)
{
	QlOSStatus err = QL_OSI_SUCCESS;
	
    err = ql_rtos_task_create(&ntp_task, 16*1024, APP_PRIORITY_ABOVE_NORMAL, "ZqNtpApp", ntp_app_thread, NULL, 5);
	if(err != QL_OSI_SUCCESS)
		ZQLOG("ntp_app init failed");

	return err;
}

